package src.array;

import java.util.Arrays;

public class no283 {
    //移动0元素到数组末尾
    public static void main(String[] args) {
        int[] arr = {0, 1, 0, 3, 12};
        int[] res = moveZeroes2(arr);
        System.out.println(Arrays.toString(res));

    }

    public static int[] moveZeroes1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }

        //右指针不断向右移动，每次右指针指向非零数，则将左右指针对应的数交换，同时左指针右移。
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            if (nums[j] != 0) {
                swapNum(nums, i, j);
                i++;
            }
            j++;
        }

        return nums;
    }

    public static int[] moveZeroes2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }
        int j = 0;  //右指针
        int i = 0;  //左指针，慢指针赋值
        while (j < nums.length) {
            if (nums[j] != 0) {
                nums[i] = nums[j];
                i++;
            }
            j++;
        }
        while (i < nums.length) {
            nums[i] = 0;
            i++;
        }
        return nums;
    }


    private static void swapNum(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }

}
